package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.excel.ExportExcel;
import com.cpit.platform.dto.LogModule;
import com.cpit.platform.dto.LogOperItem;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.common.constant.LogConstantEx;
import com.cpit.qualitycontrol.entity.SubTask;
import com.cpit.qualitycontrol.entity.WorkOrder;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 操作日志Controller
 *
 * @author Yanyongqing
 * @since 2018/3/20.
 */
@RestController
@RequestMapping(value = "/OperLog")
public class OperLogController {

    @Autowired
    private OperLogService entityService;

    /**
     * 实体类显示名称
     */
    private final String ENTITY_NAME = OperLog.ENTITY_DISPLAY_NAME;

    @ApiOperation(value = "分页查询" + ENTITY_NAME+"(TableDataQueryCondition条件)", notes = "通过TableDataQueryCondition条件查询，查询条件为:queryCond的Map条件或queryCondSimple的List<SimpleExpression>条件，或二者组合查询。返回jqGrid分页JSON形式，支持模糊查询。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。", required = true, dataType = "TableDataQueryCondition")
    })
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryOperLogJqg", method = RequestMethod.GET)
    public TableJsonData queryOperLogJqg(@ApiParam(value ="TableDataQueryCondition分页条件和其他业务条件，业务查询条件可为:queryCond的Map条件或queryCondSimple的List<SimpleExpression>条件，或二者组合查询")TableDataQueryCondition cond) {
        return this.entityService.queryLogByCondition(cond);
    }


    @ResponseBody
    @RequestMapping(value = "/getAllModules", method = RequestMethod.GET)
    public List<LogModule> getAllModules() {
        return this.entityService.getAllModules();
    }


    @ResponseBody
    @RequestMapping(value = "/getAllOperItems", method = RequestMethod.GET)
    public List<LogOperItem> getAllOperItems() {
        return this.entityService.getAllOperItem();
    }

    @ApiOperation(value = "条件删除" + ENTITY_NAME+"(TableDataQueryCondition条件)", notes = "通过TableDataQueryCondition条件删除，删除条件为:queryCond的Map条件或queryCondSimple的List<SimpleExpression>条件，或二者组合查询。返回jqGrid分页JSON形式，支持模糊查询。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。", required = true, dataType = "TableDataQueryCondition")
    })
    @ResponseBody
    @PostMapping("/deleteByCondition")
    public Result deleteByCondition(@ApiParam(value ="TableDataQueryCondition分页条件和其他业务条件，业务查询条件可为:queryCond的Map条件或queryCondSimple的List<SimpleExpression>条件，或二者组合查询")TableDataQueryCondition cond) {
        return null;
    }


    @ApiOperation(value = "导出操作日志", notes = "将系统中的操作日志导出到excel文件。")
    @RequestMapping(value = {"/exportOperLog"}, method = RequestMethod.GET)
    public String exportOperLog(HttpServletRequest request, HttpServletResponse response,
                                  @ApiParam(value = "操作人员")
                                  @RequestParam(value = "operateUser", required = true, defaultValue = "") String operateUser,
                                  @ApiParam(value = "操作项")
                                  @RequestParam(value = "operAuthorityID", required = true, defaultValue = "") String commandName,
                                  @ApiParam(value = "操作模块")
                                  @RequestParam(value = "operModelID", required = true, defaultValue = "") String moduleName,
                                  @ApiParam(value = "操作结果")
                                  @RequestParam(value = "operResult", required = true, defaultValue = "") String result) {

        String date = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        String fileName = "操作日志_" + date + ".xlsx";

        LogOperator.info(this.getClass().getName(), "result="+result);

        Map<String,Object> queryCondMap= new HashMap<String,Object>();
        queryCondMap.put("operateUser",operateUser);
        queryCondMap.put("commandName",commandName);
        queryCondMap.put("moduleName",moduleName);
        queryCondMap.put("result",result);

        List<OperLog> logList = entityService.findByQueryCondition(queryCondMap);

        String[] headers = {"操作时间", "操作人员", "操作项", "操作模块", "详细信息", "操作结果"};
        try {
            ExportExcel exportExcel = new ExportExcel(null, headers, "sheet1");

            for (OperLog log : logList) {
                int col = 0;
                Row row = exportExcel.addRow();
                exportExcel.addCell(row, col++, log.getOperateTime());
                exportExcel.addCell(row, col++, log.getOperateUser());
                exportExcel.addCell(row, col++, log.getCommandName());
                exportExcel.addCell(row, col++, log.getModuleName());
                exportExcel.addCell(row, col++, log.getDetail());
                exportExcel.addCell(row, col++, log.getResultName());
            }

            exportExcel.write(request, response, fileName).dispose();

        } catch (IOException e) {
            LogOperator.err(this.getClass().getName(), "export operLog info failed!", e);
        }
        return null;
    }
}
